#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/6/16 11:53
# @Author: Anthony (anthony66888@163.com)
# @description:
"""
import random
import time
from urllib import parse
import requests
import names
from faker import Faker

from auto_battle_room import YamlControl


class AddUser:
    def __init__(self):
        """初始化登陆后台"""
        # self.host = "https://api.muskins.com"  # 环境
        # self.token = "22_577c14956f43cc4e641fe25d88f522f2"  # 后台token
        self.config_data = YamlControl("/data/config.yaml").read_yaml()
        self.host = self.config_data["admin_host"]  # 生产环境
        self.token = self.config_data["admin_token"]  # 后台token
        self.post_headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Token": self.token,  # 后台token
            "Currentroleid": "7"
        }
        self.get_headers = {
            "Token": self.token,  # 后台token
            "Currentroleid": "7"
        }

        self.faker = Faker('pt_BR')
        self.head_pic = YamlControl("/data/head_picture.yaml").read_yaml()["head_pic"]

    def add_user(self, phone):
        """后台单次新增用户"""
        url = "/api/sys/user/customer/addCustomer"
        data = {
            "key": phone,
            "password": str(phone),
            "confirmPassword": str(phone),
            "customerType": 2,
            "remark": "对战专用辅助人员"
        }
        data = parse.urlencode(data)
        requests.post(url=self.host + url, data=data, headers=self.post_headers)
        # response = requests.post(url=self.host + url, data=data, headers=headers)
        # print(response.text)

    def get_uid(self, phone):
        """获取用户ID"""
        url = "/api/sys/user/customer/page"
        data = {
            "phone": phone,
            "totalCount": 1,
            "page": 1,
            "pageSize": 10
        }
        response = requests.get(url=self.host + url, params=data, headers=self.get_headers)
        return response.json()["data"]["pageData"][0]

    def modify_permission(self, phone):
        user_id = self.get_uid(phone)["id"]
        url = "/api/sys/user/customer/modifyPermissions"
        data = {
            "id": user_id,
            "allowMultiplayer": True,
            "allowRollRoom": True,
            "allowBattle": True,
            "allowTake": False,
            "state": False,
            "allowRecharge": True
        }
        data = parse.urlencode(data)
        try:
            requests.post(url=self.host + url, data=data, headers=self.post_headers)
        except Exception as e:
            print(f"分配权限报错：{e}")

    # def add_many_user(self, phone1, phone2):
    #     """
    #     后台批量新增用户
    #     :param phone1: 第一位用户手机号
    #     :param phone2: 最后一位手机号
    #     """
    #     for phone in range(phone1, phone2+1):
    #         self.add_user(phone)
    #         time.sleep(0.5)

    def modify_user_name(self, phone, user_id, pic, nick_name):
        """修改用户昵称 & 头像"""
        url = "/api/sys/user/customer/modifyCustomer"
        data = {
            "id": user_id,
            "customerType": 2,
            "headPic": pic,
            "nickname": nick_name,
            "phone": phone,
            "remark": "开箱、追梦专用辅助人员"
        }
        data = parse.urlencode(data)
        try:
            requests.post(url=self.host + url, data=data, headers=self.post_headers)
            print(f"修改用户{phone}的昵称为：{nick_name}")
        except Exception as e:
            print(f"新增员工报错：{e}")

    def get_random_nick_name(self):
        """获取随机昵称"""
        first = ['出金', '中金', '金色', '中', '大', '小', '金豆', '金子', '金条', '不出金',
                 '山东', '山西', '河南', '芜湖', '房山', '岭东', '西湖', '外滩', '长沙',
                 '嘎嘎', '要啥', '我要', '一手', '好运', '浮生', '一生', '一世', '一代', '一发',
                 '大使', '大师', '集团', '梭哈', '豆豆', '橙子', '伞兵', '小鸡',
                 '自行车', '印花集', '咖啡', '决斗场', '哥', '吴彦祖', '冠希哥', '怎么玩', '太美',
                 '非求', '不求', '欧皇', '没意思', '一号', '禁忌', '入魂', '入魔', '66', '88', '13'
                 ]
        second = ['大使', '大师', '集团', '梭哈', '豆豆', '橙子', '伞兵', '小鸡',
                  '自行车', '印花集', '咖啡', '决斗场', '哥', '吴彦祖', '冠希哥', '怎么玩', '太美',
                  '非求', '不求', '欧皇', '没意思', '一号', '禁忌', '入魂', '入魔',
                  '出金', '中金', '金色', '中', '大', '小', '金豆', '金子', '金条', '不出金',
                  '山东', '山西', '河南', '芜湖', '房山', '岭东', '西湖', '外滩', '长沙',
                  '嘎嘎', '要啥', '我要', '一手', '好运', '浮生', '一生', '一世', '一代', '一发'
                  ]
        nic_names = []
        for i in range(300):
            nic_names.append(random.choice(first) + random.choice(second))
        return nic_names


def batch_add_users(phone1, phone2):
    """
    后台批量新增用户
    :param phone1: 第一个用户手机号
    :param phone2: 最后一个手机号
    """
    player_config = YamlControl("/data/config.yaml")
    add_users = AddUser()
    try:
        user_list = []
        print("开始批量新增用户")
        for phone in range(phone1, phone2 + 1):
            add_users.add_user(phone)  # 新增用户
            user_list.append({'account': phone, 'password': phone})
            time.sleep(1)
        # 更新config文件的用户列表数据
        key_to_update = "player1"
        player_config.update_key_yaml(father_key=key_to_update, father_value=user_list)
        print("批量新增用户完毕")
    except Exception as e:
        print(f"新增员工报错：{e}")


if __name__ == '__main__':
    # 生产环境
    # p1 = 26111111167
    # p2 = 26111111299

    p1 = 26111111570
    p2 = 26111111799

    # 批量新增员工
    # batch_add_users(p1, p2)

    # 批量分配权限
    # add_users = AddUser()
    # for p in range(p1, p2 + 1):
    #     print(f"开始分配{p}权限")
    #     add_users.modify_permission(p)
    #     time.sleep(1)

    # 批量修改昵称
    add_users = AddUser()
    nick_names = add_users.get_random_nick_name()
    # print(nick_names)
    # nick_names = ['求求让我回个本', '亏了五个', 'TF爸爸好', 'GTRV7', '顾念', 'lisa秀', '再吃不玩',
    #               '陈刀仔', '空白', '小新', '出了继续干', 'XG没有D', '百五拉货必出哥', '不走寻常路',
    #               '南山嘎嘎飞', '法外狂人张三', '十二连败算个球', '起小飞', '兔兔大长腿', '吃不下了',
    #               '幸运欧皇', '阿良', '给点吃一下吧', '啥都不出', '反向黑才会出', '别tM吃我了', '欧皇高进',
    #               '今天是个好日子', '给你爷出货', 'Bigdick', '室友最后一眼出', '鹿是我er', '我死了', '零提怎么破',
    #               '吃点药丸', '拉血压', '车轱辘没了', '一直出一直吃', '爽歪歪', '一滴都不给', '迈阿密没了',
    #               '低保户', '太南了', '6连败该出了', '碗泥麻个笔', '太对了', '虚坤大傻子', '缅甸北直达',
    #               'roll中一个', '再不出跳了', '曹贼没有屌', '冲击星来一发', '法兰克福', '怎么不让充了', '梦碎了',
    #               '睡不着', '求求了', '锁了?']
    for p in range(p1, p2 + 1):
        res = add_users.get_uid(p)
        if res["nickname"][:2] == "TF":
            uid = res["id"]
            head_pic = res["headPic"]
            nick = random.choice(nick_names)
            add_users.modify_user_name(p, uid, head_pic, nick)
            nick_names.remove(nick)
            if len(nick_names) == 0:
                print("昵称已用完")
                break

